﻿using AutoBlogger.DB;
using HtmlAgilityPack;
using JoeBlogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AutoBlogger.Tool
{
    internal class WordPressClient
    {
        WordPressWrapper wpWrapper;
        internal WordPressClient(WordPressWrapper _wpWrapper)
        {
            wpWrapper = _wpWrapper;
        }

        internal int NewPost(BlogModel item)
        {
            HtmlDocument htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(item.Content);
            var imgs = htmlDoc.DocumentNode.Descendants("img");

            foreach (var img in imgs)
            {
                var imgUrl = img.Attributes["src"].Value;
                if (imgUrl.EndsWith(".thumb"))
                {
                    continue;
                }
                var bits = NetClient.DownloadImage(imgUrl);
                if (bits == null)
                {
                    continue;
                }

                try
                {
                    var file = wpWrapper.UploadFile(new Data()
                    {
                        Name = imgUrl.Substring(imgUrl.LastIndexOf('/') + 1),
                        Type = "image/jpeg",
                        Overwrite = true,
                        Bits = bits
                    });

                    var index = img.ParentNode.ChildNodes[img];
                    img.ParentNode.ChildNodes[index].Attributes["src"].Value = file.URL;
                }
                catch (Exception ex)
                {
                    continue;
                }
            }

            item.Content = htmlDoc.DocumentNode.OuterHtml;

            int post_id = wpWrapper.NewPost(new Post()
            {
                Body = item.Content,
                //PostType = "Post",
                DateCreated = DateTime.Now,
                Title = item.Title
            }, true);

            return post_id;
        }
    }
}
